<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 打印机管理
 *
 * @icon fa fa-circle-o
 */
/**
 * @method array get(string $uri, array $query = [])
 * @method array put(string $uri, array $form_params = [])
 * @method array post(string $uri, array $form_params = [])
 * @method array patch(string $uri, array $form_params = [])
 * @method array delete(string $uri, array $form_params = [])
 */
class Dayin extends Backend
{

    /**
     * 基本请求地址
     */
    const BASE_URI = 'https://open.spyun.net/v1/';

    /**
     * 连接超时时间
     */
    const CONNECTTIMEOUT = 1;

    /**
     * 超时时间
     */
    const TIMEOUT = 4;

    /**
     * @var string
     */
    protected $appid="sp669f7f22e5250";

    /**
     * @var $appsecret
     */
    protected $appsecret="81288879aa722dd2367f9b883f0e5830";

    /**
     * @var string
     */
    protected $message;

    /**
     * Dayin模型对象
     * @var \app\admin\model\Dayin
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Dayin;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    //订单打印
    public function order_print(){
        $ids = input('ids','');//订单id
        $type = input('type','');
        if($type == 1){
            $list = db('order')->where(['id'=>['in',$ids]])->select();
        }else{
            $list = db('splicingorder')->where(['id'=>['in',$ids]])->select();
        }
        //查询打印机
        $dayinji = db("dayin")->where(['status'=>'1'])->find();
        if(empty($dayinji)){
            $this->error("请先设置默认打印机");
        }
        $times = 1;
        foreach($list as $v){
            $content = "<C>"."打印小票"."</C>";
            $content .= "订单号：".$v['order_sn']."<BR>";
//            $content .= "数量：".$v['num']."<BR>";
            if($type == 1){
                $content .= "取餐点：".$v['pickup_name']."<BR>";

                $order_goods = db("order_goods")->where(['order_id'=>$v['id']])->select();
            }else{
                $content .= "取餐地址：".$v['address']."<BR>";
                $content .= "联系人：".$v['name']."<BR>";
                $content .= "电话：".$v['phone']."<BR>";

                $order_goods = db("splicingorder_goods")->where(['order_id'=>$v['id']])->select();
            }
            $content .= "--------------------------------"."<BR>";

            foreach($order_goods as $val){
                $val['aux'] = json_decode($val['aux'],true);
                $content .= $v['posts_name']."<BR>";
                foreach($val['aux'] as $v2){
                    $content .= $v2['name']."<BR>";
                }
                $content .= "--------------------------------"."<BR>";

            }

            $content .= "<R>金额：".$v['money']."</R><BR>";
            $content .= "下单时间：".date("Y-m-d H:i:s",$v['addtime'])."<BR>";
            $res = $this->post("printer/print", $this->makeRequestParams([
                'sn' => $dayinji['sn'],
                'content' => $content,
                'times' => $times
            ]));
            dump($res);die;
        }

        dump($list);die;
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $res = $this->post('printer/add', $this->makeRequestParams([
                'sn'    => $params['sn'],
                'pkey'  => $params['pkey'],
                'name'  => $params['name'],
            ]));
            if($res['errorcode'] != 0){
                $this->error($res['errormsg']);
            }

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                $sn = $item['sn'];//打印机编号(查看打印机底部标签)
                //删除打印机
                $res =  $this->delete('printer/delete', $this->makeRequestParams([
                    'sn' => $sn
                ]));

            }

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    /**
     * 创建请求参数
     * @param array $params
     * @return array
     */
    public function makeRequestParams(array $params = [])
    {
        $params['appid'] = $this->appid;
        $params['timestamp'] = time();
        $params['sign'] = $this->makeSign($params);
        return $params;
    }

    /**
     * 创建签名
     * @param array $params
     * @return string
     */
    public function makeSign(array $params)
    {
        ksort($params);
        $sign = "";
        foreach ($params as $k => $v) {
            if ($k != "sign" && $k != "appsecret" && $v !== "" && !is_array($v) && !is_null($v)) {
                $sign .= $k . "=" . $v . "&";
            }
        }
        $sign = rtrim($sign, '&');
        $sign .= "&appsecret=" . $this->appsecret;

        return strtoupper(md5($sign));
    }

    /**
     * @param $method
     * @param $args
     * @return array
     * @throws Exception
     */
    public function __call($method, $args)
    {
        if (count($args) < 1) {
            throw new \InvalidArgumentException(
                'Magic request methods require a URI and optional options array'
            );
        }

        $method = strtoupper($method);
        $uri = $args[0];
        $params = isset($args[1]) ? $args[1] : [];
        return $this->_request($method, $uri, $params);
    }
    /**
     * @param string $method
     * @param string $uri
     * @param array $params
     * @return array
     * @throws Exception
     */
    protected function _request($method, $uri, array $params = [])
    {


        $ch = curl_init();
        $url = self::BASE_URI . $uri;
        if ($method == 'GET' || $method == 'DELETE') {
            $url .= '?' . http_build_query($params);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        }
        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CONNECTTIMEOUT);
//        curl_setopt($ch, CURLOPT_TIMEOUT, self::TIMEOUT);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $http_error = curl_error($ch);
        $http_errno = curl_errno($ch);
        curl_close($ch);

        $response = json_decode($response, 1);
        return $response;
    }
}
